﻿using GuanYijia.DoMain;
using GuanYijia.Repository;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Reflection;
using System.Security.Claims;
using System.Text;

namespace GuanYiJia.WebApi
{//全局日志加载
    public class CustomActionFilterAsyncAttribute : IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            // 检查是否存在 SkipCustomFilterAttribute 特性
            var hasSkipFilterAttribute = context.ActionDescriptor.EndpointMetadata
                .Any(em => em is SkipCustomFilterAttribute);
            if (hasSkipFilterAttribute)
            {
                await next();
                return;
            }
            //...（原过滤器中的其他代码，省略部分以节省篇幅）
            // 执行动作并获取结果
            var resultContext = await next();
            // 开始时间，用于计算响应时长
            var startTime = DateTime.Now;
            // 计算响应时长
            var duration = DateTime.Now - startTime;
            // 获取 HttpContext
            var httpContext = resultContext.HttpContext;
            // 获取请求地址
            var requestUrl = $"{httpContext.Request.Scheme}://{httpContext.Request.Host}{httpContext.Request.Path}{httpContext.Request.QueryString}";
            // 获取用户 IP 地址
            var userIp = httpContext.Connection.RemoteIpAddress?.ToString();

            // 检查是否存在 X-Forwarded-For 头，它可能包含真实客户端 IP
            var forwardedFor = httpContext.Request.Headers["X-Forwarded-For"].ToString();
            if (!string.IsNullOrEmpty(forwardedFor))
            {
                userIp = forwardedFor.Split(',')[0].Trim();
            }
            else if (httpContext.Connection.RemoteIpAddress.IsIPv6LinkLocal)
            {
                // 如果是本地 IPv6 地址，则映射到 IPv4
                userIp = httpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
            }
            // 获取浏览器类型
            var userAgent = httpContext.Request.Headers["User-Agent"].ToString();
            // 获取请求参数（查询字符串和请求体）
            var queryParameters = httpContext.Request.Query.ToDictionary(k => k.Key, v => v.Value.ToString());
            string requestBody = null;
            // 如果是 POST 请求，可以读取请求体（需要确保只读取一次）
            if (httpContext.Request.Method == HttpMethods.Post)
            {
                httpContext.Request.EnableBuffering();
                using (var reader = new StreamReader(httpContext.Request.Body, Encoding.UTF8, leaveOpen: true))
                {
                    requestBody = await reader.ReadToEndAsync();
                    // Reset the body stream position for further processing
                    httpContext.Request.Body.Position = 0;
                }
            }
            // 响应状态码
            var statusCode = resultContext.HttpContext.Response.StatusCode;
            // 获取异常信息（如果有的话）
            var exception = resultContext.Exception;
            var logType = exception == null ? "系统" : "异常";
            // 现在可以使用 value 了
            var actionAdd = context.HttpContext.RequestServices.GetRequiredService<IBaseRepository<CustomLog>>();
            var httpContextAccessor = context.HttpContext.RequestServices.GetRequiredService<IHttpContextAccessor>();

            // 根据控制器名称来推断操作模块
            string module = "";
         
            string controllerName = context.ActionDescriptor.RouteValues["controller"];
            string actionName = context.ActionDescriptor.RouteValues["action"];
            if (actionName == "Login")
            {
                module = "登录模块";
            }else if (actionName=="GetProductShow")
            {
                module = "获取商品列表模块";
            }else if (actionName == "GetMenus")
            {
                module = "获取菜单表";
            }
            else if (actionName == "GetRoleList")
            {
                module = "获取角色列表";
            }
            else if (actionName == "AddRole")
            {
                module = "添加角色模块";
            }
            else if (actionName == "GetRolePermisssionById")
            {
                module = "根据权限列表获取角色";
            }
            else if (actionName == "AddRolePerssion")
            {
                module = "添加角色权限";
            }
            else if (actionName == "AddUser")
            {
                module = "添加用户";
            }
            else if (actionName == "GetRole")
            {
                module = "获取角色";
            }
            else if (actionName == "DeleteSalesOrder")
            {
                module = "销售订单逻辑删除";
            }
            else if (actionName == "RangeDeleteSalesOrder")
            {
                module = "销售订单批量删除";
            }
            
            else if (actionName == "DeleteRequisition")
            {
                module = "采购管理请购单逻辑单删";
            }
            else if (actionName == "RangeDeleteRequisition")
            {
                module = "采购管理请购单逻辑批删";
            }
            else if (actionName == "DeletePurchaseOrder")
            {
                module = "采购管理采购订单逻辑单删";
            }
            else if (actionName == "RangeDeletePurchaseOrder")
            {
                module = "采购管理采购订单逻辑批删";
            }
            else if (actionName == "GetMaterialCategoryTree")
            {
                module = "商品类型的级联";
            }
            else if (actionName == "InsertMaterialCategory")
            {
                module = "商品类型的添加";
            }
            else if (actionName == "GetMaterialCategoryOne")
            {
                module = "获取单条商品类型";
            }
            else if (actionName == "UpdateMaterialCategoryOne")
            {
                module = "修改商品类型";
            }
            else if (actionName == "DeleteMaterialCategoryRange")
            {
                module = "删除商品类型";
            }
            else if (actionName == "GetProductShow")
            {
                module = "商品信息展示";
            }
            else if (actionName == "AddProductAndOther")
            {
                module = "添加商品";
            }
            else if (actionName == "GetProductOne")
            {
                module = "获取单条商品信息";
            }
            else if (actionName == "UpdateProductAndOther")
            {
                module = "修改商品信息";
            }
            else if (actionName == "DeleteProductRange")
            {
                module = "删除商品信息";
            }
            else if (actionName == "DeleteSalesOutbound")
            {
                module = "销售出库逻辑删除";
            }
            else if (actionName == "RangeDeleteSalesOutbound")
            {
                module = "销售出库批量删除";
            }
            else if (actionName == "AddSupplier")
            {
                module = "基本资料供应商信息添加";
            }
            else if (actionName == "GetSuppLierInfo")
            {
                module = "基本资料供应商信息反填";
            }
            else if (actionName == "UpdateSupplier")
            {
                module = "基本资料供应商信息修改";
            }
            else if (actionName == "DeleteSupplier")
            {
                module = "基本资料供应商信息逻辑单删";
            }
            else if (actionName == "RangeDeleteSupplier")
            {
                module = "基本资料供应商信息逻辑批删";
            }
            else if (actionName == "UpdateCanenable")
            {
                module = "基本资料供应商信息启用";
            }
            else if (actionName == "UpdateDisable")
            {
                module = "基本资料供应商信息禁用";
            }
            else if (actionName == "DeleteCustomer")
            {
                module = "基本资料客户信息逻辑单删";
            }
            else if (actionName == "RangeDeleteCustomer")
            {
                module = "基本资料客户信息逻辑批删";
            }
            else if (actionName == "AddCustomer")
            {
                module = "基本资料客户信息添加";
            }
            else if (actionName == "GetCustomerInfo")
            {
                module = "基本资料客户信息反填";
            }
            else if (actionName == "UpdateCustomer")
            {
                module = "基本资料客户信息修改";
            }
            else if (actionName == "UpdateCustomerCanenable")
            {
                module = "基本资料客户信息启用";
            }
            else if (actionName == "UpdateCustomerDisable")
            {
                module = "基本资料客户信息禁用";
            }
            string actionDetail = $"{controllerName} - {actionName}";

           
            var claimsPrincipal = httpContextAccessor.HttpContext.User;
            // 指定要查找的自定义声明类型
            var custom_id = "id";
            var userId = claimsPrincipal.FindFirst(custom_id)?.Value;
            var username = claimsPrincipal.FindFirst(ClaimTypes.Name)?.Value;
            CustomLog customLog = new CustomLog();  
            customLog.user_id = Convert.ToInt32(userId);
            customLog.operation = module;
            customLog.content = actionDetail;
            customLog.loginname= username;
            customLog.client_ip = userIp;
            customLog.create_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff");
            await actionAdd.InsertAsync(customLog);

        }
    }
}
